use std::io::{Stdin, Stdout, Write};

use crate::calc::calculate;

pub fn start(stdin: Stdin, mut stdout: Stdout) {
   println!("支持 +, -, *, /, ^, () 符号");
   println!("按q退出");

   loop {
      write!(stdout, "请输入算术表达式> ")
         .expect("should have written prompt string >>");
      stdout.flush().expect("should have flushed stdout!");

      let mut input = String::new();

      if let Err(e) = stdin.read_line(&mut input) {
         writeln!(stdout, "Error: {e}")
            .expect("should have written error message");
         return;
      }

      let input = input.trim();
      if input == "q" {
         break;
      } else if input.is_empty() {
         continue;
      }

      match calculate(input) {
         Ok(result) => writeln!(stdout, "{result}")
            .expect("parsed program should be written to stdout"),
         Err(err) => println!("{err}"),
      }
   }
}
